package pro.seac.twitter.web;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.commons.lang3.ArrayUtils;

import com.vaadin.data.Container;
import com.vaadin.ui.Table;
import com.vaadin.ui.Table.ColumnGenerator;

public class UIUtils {

	public static TableBuilder wrapTable(Table existingTable) {
		existingTable.setSizeFull();
		existingTable.setSelectable(false);
		existingTable.setFooterVisible(false);
		existingTable.setColumnReorderingAllowed(false);
		existingTable.setColumnCollapsingAllowed(false);
		existingTable.setNullSelectionAllowed(false);
		return new TableBuilder(existingTable);
	}

	public static TableBuilder newTable() {
		return wrapTable(new Table());
	}

	public static class TableBuilder {
		private Table instance;

		TableBuilder(Table instance) {
			this.instance = instance;
		}

		public TableBuilder withContainer(Container newDataSource, String... containerVisibleColumns) {
			Object[] columns = instance.getVisibleColumns();
			instance.setContainerDataSource(newDataSource);
			if (containerVisibleColumns != null) {
				Object[] visibleColumns = ArrayUtils.addAll(columns, (Object[]) containerVisibleColumns);
				instance.setVisibleColumns(visibleColumns);
			}
			return this;
		}

		TableBuilder withColumn(String columnId, int columnWidth) {
			if (columnWidth == -1) {
				instance.setColumnExpandRatio(columnId, 1.0F);
			} else {
				instance.setColumnWidth(columnId, columnWidth);
			}
			instance.setColumnHeader(columnId, Messages.message("table.column." + columnId));
			return this;
		}

		public TableBuilder withColumn(String columnId, int columnWidth, ColumnGenerator generator) {
			withColumn(columnId, columnWidth);
			if (generator != null) {
				instance.addGeneratedColumn(columnId, generator);
			} else {
				Set<Object> columns = new LinkedHashSet<Object>(Arrays.asList(instance.getVisibleColumns()));
				if (!columns.contains(columnId)) {
					columns.add(columnId);
					instance.setVisibleColumns(columns.toArray());
				}
			}
			return this;
		}

		public TableBuilder withColumn(String id, int width, Class<?> type, Object defaultValue) {
			withColumn(id, width);
			instance.addContainerProperty(id, type, defaultValue);
			return this;
		}

		public Table build() {
			return instance;
		}
	}
}
